package com.tc.dispatch.web.schedule.order;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.tc.dispatch.gsalgorithm.spec.parse;
import com.tc.dispatch.gsservice.basic.common.regulation;
import com.tc.dispatch.gsservice.ejb.GSServiceLocal;
import com.tc.dispatch.gsservice.exception.GSException;
import com.tc.dispatch.gsservice.model.OrderSumMain;
import com.tc.dispatch.gsservice.model.OrderSumSub;
import com.tc.dispatch.gsservice.model.ProcessStep;
import com.tc.dispatch.web.gsservice.gsHelper;
import com.tc.dispatch.web.model.combinedOrder;
import com.tc.dispatch.web.util.DateJsonValueProcessor;
import com.tc.dispatch.web.util.FloatJsonValueProcessor;
import com.tc.dispatch.web.util.tools;

public class orderSaveIndex extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public orderSaveIndex() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		if (action == null)
			action = "";

		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		if (action == null)
			action = "";

		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		HttpSession sess = request.getSession();
		List processList, processListDef;
		OrderSumMain osm = new OrderSumMain();
		OrderSumMain osmDef = new OrderSumMain();
		String pos = "0";
		if (sess.getAttribute("position") != null) {
			pos = (String) sess.getAttribute("position");
		}
		;
		if (action.equals("default")) {
			/* 将两个加工列表显示出来,并且加上剩余的那些参数都显示出来 */
			if (Integer.parseInt(pos) == 4)// 表示 刚开始
			{

				try {

					osm = (OrderSumMain) sess.getAttribute("OrderSumMain");
					osmDef = (OrderSumMain) sess
							.getAttribute("OrderSumMainDef");

					/* 这里需要设置包装费，产品成本，利润，后道成品率 */
					float d1 = regulation.getDensity(osm.getSsign());
					float v=parse.parseSpec(osm.getSpec()).volume();
					float net=v*d1/1000000;
					//osm.setBaozhuangfei(regulation.baoZhuangPrice*net);

					d1 = regulation.getDensity(osmDef.getSsign());
					
					//osmDef.setBaozhuangfei(regulation.baoZhuangPrice*net);

					/* 最后产品成本,成品率 */
					List retList = gss.findOrderSumSub(" where ordersumid="
							+ osm.getId() + " order by processPos desc");
					if (retList.size() < 1)
						throw new Exception();
					Iterator it = retList.iterator();
					float p1 = 1, temp;
					OrderSumSub oss;
					while (it.hasNext()) {
						oss = (OrderSumSub) it.next();
						p1 *= oss.getProcessYield().floatValue();
					}
					oss = (OrderSumSub) retList.get(0);
					//osm.setProduct_cost_last(oss.getUntilPrice().floatValue()/regulation.baoZhuangYield);
				//	osm.setHoudao_yield(p1);

					retList = gss.findOrderSumSub(" where ordersumid="
							+ osmDef.getId() + " order by processPos desc");
					if (retList.size() < 1)
						throw new Exception();
					it = retList.iterator();
					p1 = 1;
					while (it.hasNext()) {
						oss = (OrderSumSub) it.next();
						p1 *= oss.getProcessYield().floatValue();
					}
					oss = (OrderSumSub) retList.get(0);
					//osmDef.setProduct_cost_last(oss.getUntilPrice().floatValue()/regulation.baoZhuangYield);
					//osmDef.setHoudao_yield(p1);
					/* 设置利润 */
					osm.jieSuanLiRun();
					osmDef.jieSuanLiRun();

					/* 输出 */

				} catch (Exception e) {
					out.print("{success:false, data:'false'}");
				}

			} else {
				osm = (OrderSumMain) sess.getAttribute("OrderSumMain");
				osmDef = (OrderSumMain) sess.getAttribute("OrderSumMainDef");
			}
			JSONObject json = new JSONObject();
			JsonConfig cfg = new JsonConfig();
			cfg.registerJsonValueProcessor(java.util.Date.class,
					new DateJsonValueProcessor());
			cfg.registerJsonValueProcessor(java.sql.Date.class,
					new DateJsonValueProcessor());

			// BeanUtils.copyProperties();
			json.put("totalProperty", new Integer(1));
			List ret = new ArrayList();
			combinedOrder corder = new combinedOrder();
			//corder.setOsm(osm.convertToString());
			//corder.setOsm2(osmDef.convertToString());
			ret.add(corder);
			// ret.addAll(retList);

			JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
			json.put("osmRoot", arr);

			response.getWriter().print(json);
		} else if (action.equals("defaultList")) {
			try {
				processList = (List) sess.getAttribute("processList");

				OrderSumSub oss=(OrderSumSub)processList.get(0);
				int osmid=oss.getOrderSumId().intValue();
				List retList=gss.findOrderSumSub("where ordersumid="+osmid+" order by processPos");
				
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.lang.Float.class, new FloatJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(retList.size()));
				List ret = new ArrayList();

				// ret.addAll(retList);

				JSONArray arr = JSONArray.fromObject(retList.toArray(), cfg);
				json.put("processRoot", arr);

				response.getWriter().print(json);
			} catch (Exception e) {
				out.print("{success:false, data:'false'}");
			}

		} else if (action.equals("defaultList2")) {
			try {

				processListDef = (List) sess.getAttribute("processListDef");
				OrderSumSub oss=(OrderSumSub)processListDef.get(0);
				int osmid=oss.getOrderSumId().intValue();
				List retList=gss.findOrderSumSub("where ordersumid="+osmid+" order by processPos");
				
				
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.lang.Float.class, new FloatJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(retList.size()));
				List ret = new ArrayList();

				// ret.addAll(retList);

				JSONArray arr = JSONArray.fromObject(retList.toArray(), cfg);
				json.put("processRoot", arr);

				response.getWriter().print(json);
			} catch (Exception e) {
				out.print("{success:false, data:'false'}");
			}

		} else if (action.equals("update")) {
			/* specType,scheme */

			float baozhuangfei = Float.parseFloat(request
					.getParameter("baozhuangfei"));
			float houdao_yield = Float.parseFloat(request
					.getParameter("houdao_yield"));
			float product_cost_last = Float.parseFloat(request
					.getParameter("product_cost_last"));
			java.util.Date date1 = tools.stringToDate(request
					.getParameter("date1"));
			float ordercost = Float.parseFloat(request
					.getParameter("ordercost"));
			float lirun = Float.parseFloat(request.getParameter("lirun"));
			String bz = request.getParameter("bz");
			String maker = request.getParameter("maker");
			java.util.Date makeDate = tools.stringToDate(request
					.getParameter("makeDate"));
			
			float baozhuangfei2 = Float.parseFloat(request
					.getParameter("baozhuangfei2"));
			float houdao_yield2 = Float.parseFloat(request
					.getParameter("houdao_yield2"));
			float product_cost_last2 = Float.parseFloat(request
					.getParameter("product_cost_last2"));
			java.util.Date date12 = tools.stringToDate(request
					.getParameter("date12"));
			float ordercost2 = Float.parseFloat(request
					.getParameter("ordercost2"));
			float lirun2 = Float.parseFloat(request.getParameter("lirun2"));
			String bz2 = request.getParameter("bz2");
			String maker2 = request.getParameter("maker2");
			java.util.Date makeDate2 = tools.stringToDate(request
					.getParameter("makeDate2"));
			
			
			
			osm = (OrderSumMain) sess.getAttribute("OrderSumMain");
			osmDef = (OrderSumMain) sess.getAttribute("OrderSumMainDef");
			
			//osm.setBaozhuangfei(baozhuangfei);
			//osm.setHoudao_yield(houdao_yield);
			//osm.setProduct_cost_last(product_cost_last);
			osm.setDate1(date1);
			//osm.setOrdercost(ordercost);
			//osm.setLirun(lirun);
			osm.setBz(bz);
			osm.setMaker(maker);
			osm.setMakeDate(makeDate);
			
			//osmDef.setBaozhuangfei(baozhuangfei2);
			//osmDef.setHoudao_yield(houdao_yield2);
			//osmDef.setProduct_cost_last(product_cost_last2);
			osmDef.setDate1(date12);
			//osmDef.setOrdercost(ordercost2);
			//osmDef.setLirun(lirun2);
			osmDef.setBz(bz2);
			osmDef.setMaker(maker2);
			osmDef.setMakeDate(makeDate2);
			osm = (OrderSumMain) sess.getAttribute("OrderSumMain");
			osmDef = (OrderSumMain) sess.getAttribute("OrderSumMainDef");

			try {
				gss.updateOrderSumMain(osm);
				gss.updateOrderSumMain(osmDef);
				
				//这里设置成功的标示符。
				sess.removeAttribute("orderSumMain");
				sess.removeAttribute("OrderSumMainDef");
				sess.setAttribute("task", "finished");

			} catch (Exception e) {
				out.print("{success:false, data:'false'}");
			}
			out.print("{success:true, data:'sucess'}");

		} else if (action.equals("sort")) {
			try {
				List sortList = gss.findProcessStep("");
				Iterator it = sortList.iterator();
				ProcessStep ps;
				List ret = new ArrayList();
				List retList = new ArrayList();

				while (it.hasNext()) {
					ps = (ProcessStep) it.next();
					if (ret.indexOf(ps.getSpecName()) < 0) {
						ret.add(ps.getSpecName());
						retList.add(ps);
					} else {
						// sortList.remove(ps);
					}
				}
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(retList.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
			} catch (GSException e) {
				out.print("{success:false, data:'false'}");
			}

		} else if (action.equals("scheme")) {
			try {
				String sort = request.getParameter("sortType");
				List sortList = gss.findProcessStep(" where specName='" + sort
						+ "'");
				Iterator it = sortList.iterator();
				ProcessStep ps;
				List ret = new ArrayList();
				List retList = new ArrayList();
				while (it.hasNext()) {
					ps = (ProcessStep) it.next();
					if (ret.indexOf(new Integer(ps.getScheme())) < 0) {
						ret.add(new Integer(ps.getScheme()));
						retList.add(ps);
					}
				}
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				// BeanUtils.copyProperties();
				// json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(retList.toArray(), cfg);
				json.put("root", arr);
				// json.

				response.getWriter().print(json);
			} catch (GSException e) {
				out.print("{success:false, data:'false'}");
			}
		} else if (action.equals("step")) {
			try {
				String sort = request.getParameter("sortType");
				String scheme = request.getParameter("scheme");
				List sortList = gss.findProcessStep(" where specName='" + sort
						+ "' and scheme=" + scheme);
				List ret = sortList;
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
			} catch (GSException e) {
				out.print("{success:false, data:'false'}");
			}
		}

		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
